﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Common;
using SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Project;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.ProjectManager;
using SJ.Platform.Extend.IOC.CurrentUser;
using SJ.Platform.Extend.ModelExtend;
using SJ.Platform.Extend.ModelExtend.ProjectExt;
using SJ.Platform.Extend.Request;
using SJ.Platform.Extend.Response;
using System.Security.Cryptography;

namespace SJ.Platform.Api.Controllers.ProjectManager
{
    /// <summary>
    /// 项目需求操作类
    /// </summary>
    [Route(GlobalVariableHandle.Scope_Api + "/ProjectRequirement")]
    [ApiController]
    [Authorize(GlobalVariableHandle.Scope_Api)]
    public class ProjectRequirementController : ControllerBase
    {
        private readonly SJDBContext _context;
        private readonly ICurrentUser _currentUser;
        private readonly Project_Requirement_MainHandle _mainHandle;
        private readonly Project_Requirement_InfoHandle _infoHandle;
        private readonly Project_Requirement_FeatureHandle _featureHandle;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库</param>
        /// <param name="currentUser">当前用户</param>
        public ProjectRequirementController(SJDBContext dbContext, ICurrentUser currentUser)
        {
            _context = dbContext;
            _currentUser = currentUser;
            _mainHandle = new Project_Requirement_MainHandle(dbContext);
            _infoHandle = new Project_Requirement_InfoHandle(dbContext);
            _featureHandle = new Project_Requirement_FeatureHandle(dbContext);
        }

        /// <summary>
        /// 编制需求
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("FormulateProjectRequirementAsync")]
        public async Task<IActionResult> FormulateProjectRequirementAsync([FromBody] ProjectRequirementMainExtend model)
        {
            try
            {

                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    //先清空之前的记录
                    bool actionResult = await _mainHandle.DeleteByProjectIdAsync(model.ProjectId) && await _infoHandle.DeleteByProjectIdAsync(model.ProjectId) && await _featureHandle.DeleteByProjectIdAsync(model.ProjectId);

                    //主记录
                    ProjectRequirementMain requirementMain = model.ExtMapToEntity<ProjectRequirementMain, ProjectRequirementMainExtend>();
                    requirementMain.Status = 1;
                    requirementMain.AddTime = requirementMain.AddTime == null ? DateTime.Now : requirementMain.AddTime;
                    requirementMain.AddUserId = string.IsNullOrWhiteSpace(requirementMain.AddUserId) ? _currentUser.UserId : requirementMain.AddUserId;
                    requirementMain.EditUserId = _currentUser.UserId;
                    requirementMain.EditTime = DateTime.Now;

                    List<ProjectRequirementInfo> infoList = new List<ProjectRequirementInfo>();
                    List<ProjectRequirementFeature> featureList = new List<ProjectRequirementFeature>();
                    DealRequirement(model.Requirements, infoList, featureList);

                    //保存新的记录
                    actionResult = await _mainHandle.CreateAsync(requirementMain);
                    if (infoList.Count > 0 && actionResult)
                    {
                        actionResult = await _infoHandle.BatchCreateAsync(infoList);
                    }
                    if (featureList.Count > 0 && actionResult)
                    {
                        actionResult = await _featureHandle.BatchCreateAsync(featureList);
                    }

                    return actionResult;
                });               

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "项目需求添加" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "项目需求添加失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 更新项目需求指定的内容
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UpdateRequirementMainSpecificContentAsync")]
        public async Task<IActionResult> UpdateRequirementMainSpecificContentAsync([FromBody] ProjectRequirementMainExtend model)
        {
            try
            {
                //默认更新最后修改时间和修改人
                model.EditTime = DateTime.Now;
                model.EditUserId = _currentUser.UserId;
                model.UpdateProperties.Add("EditTime");
                model.UpdateProperties.Add("EditUserId");
                bool result = await _mainHandle.UpdateRequirementMainSpecificContentAsync(model);
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "项目更新" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "项目更新失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 递归处理需求细则和需求下的功能
        /// </summary>
        /// <param name="list"></param>
        /// <param name="infoList"></param>
        /// <param name="featureList"></param>
        private void DealRequirement(List<ProjectRequirementInfoExtend> list, List<ProjectRequirementInfo> infoList, List<ProjectRequirementFeature> featureList)
        {
            try
            {
                foreach (ProjectRequirementInfoExtend item in list)
                {
                    ProjectRequirementInfo info = item.ExtMapToEntity<ProjectRequirementInfo, ProjectRequirementInfoExtend>();
                    infoList.Add(info);

                    if (item.ChildFeatures != null && item.ChildFeatures.Count > 0)
                    {
                        foreach (ProjectRequirementFeatureExtend featureExtend in item.ChildFeatures)
                        {
                            ProjectRequirementFeature feature = featureExtend.ExtMapToEntity<ProjectRequirementFeature, ProjectRequirementFeatureExtend>();

                            featureList.Add(feature);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 根据项目ID获取项目需求
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpGet("GetRequirementDetailByProjectIdAsync/{projectId}")]
        public async Task<IActionResult> GetRequirementDetailByProjectIdAsync(string projectId)
        {
            try
            {
                ProjectRequirementMainExtend mainExtend = await _mainHandle.GetEntityByProjectIdAsync(projectId);
                if (mainExtend.Requirements == null)
                {
                    mainExtend.Requirements = new List<ProjectRequirementInfoExtend>();
                }
                mainExtend.Requirements = await _infoHandle.GetRequirementsAndFeaturesByProjectIdAsync(projectId);
                return Ok(ApiNormalResponse<ProjectRequirementMainExtend>.SetResponse(ApiResponseStatus.Success, "查询成功", mainExtend)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<ProjectRequirementMainExtend>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new ProjectRequirementMainExtend { }));
            }
        }

        /// <summary>
        /// 根据项目ID获取项目需求基本信息
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpGet("GetRequirementEntityByProjectIdAsync/{projectId}")]
        public async Task<IActionResult> GetRequirementEntityByProjectIdAsync(string projectId)
        {
            try
            {
                ProjectRequirementMainExtend mainExtend = await _mainHandle.GetEntityByProjectIdAsync(projectId);               
                return Ok(ApiNormalResponse<ProjectRequirementMainExtend>.SetResponse(ApiResponseStatus.Success, "查询成功", mainExtend)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<ProjectRequirementMainExtend>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new ProjectRequirementMainExtend { }));
            }
        }

        /// <summary>
        /// 根据需求ID获取需求详情
        /// </summary>
        /// <param name="requirementId"></param>
        /// <returns></returns>
        [HttpGet("GetRequirementDetailByRequirementIdAsync/{requirementId}")]
        public async Task<IActionResult> GetRequirementDetailByRequirementIdAsync(string requirementId)
        {
            try
            {
                var result = await _infoHandle.GetRequirementsAndFeaturesByRequirementIdAsync(requirementId);
                return Ok(ApiNormalResponse<List<ProjectRequirementInfoExtend>>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<ProjectRequirementInfoExtend>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new ProjectRequirementInfoExtend { }));
            }
        }

        /// <summary>
        /// 根据项目ID获取项目需求树
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpGet("GetProjectRequirementTreeAsync/{projectId}")]
        public async Task<IActionResult> GetProjectRequirementTreeAsync(string projectId)
        {
            try
            {
                var result = await _infoHandle.GetRequirementsByProjectIdAsync(projectId);
                return Ok(ApiNormalResponse<List<ProjectRequirementInfoExtend>>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<ProjectRequirementInfoExtend>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new List<ProjectRequirementInfoExtend> { }));
            }
        }

        /// <summary>
        /// 根据ID获取需求信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetRequirementDetailByIdAsync/{id}")]
        public async Task<IActionResult> GetRequirementDetailByIdAsync(string id)
        {
            try
            {
                //需求主记录
                ProjectRequirementMainExtend mainExtend = await _mainHandle.GetEntityByIdAsync(id);
                //获取需求细则
                if (mainExtend.Requirements == null)
                {
                    mainExtend.Requirements = new List<ProjectRequirementInfoExtend>();
                }
                mainExtend.Requirements = await _infoHandle.GetRequirementsAndFeaturesByProjectIdAsync(mainExtend.ProjectId);

                return Ok(ApiNormalResponse<ProjectRequirementMainExtend>.SetResponse(ApiResponseStatus.Success, "查询成功", mainExtend)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<ProjectRequirementMainExtend>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new ProjectRequirementMainExtend { }));
            }
        }

        /// <summary>
        /// 获取所有项目需求
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("GetProjectRequirementsAsync")]
        public async Task<IActionResult> GetProjectRequirementsAsync([FromBody] ApiPageQueryRequest<ProjectRequirementMainExtend> request)
        {
            try
            {
                var result = await _mainHandle.GetProjectRequirementsAsync((int)request.PageIndex, (int)request.PageSize, _currentUser.UserId, ApiPageQueryRequest<ProjectRequirementMainExtend>.GenerateCondition(request.Condition));

                return Ok(ApiPageQueryResponse<List<ProjectRequirementMainExtend>>.SetResponse(ApiResponseStatus.Success, "查询成功", (int)request.PageIndex, (int)request.PageSize, result.count, result.mainExtends)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiPageQueryResponse<List<ProjectRequirementMainExtend>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, (int)request.PageIndex, (int)request.PageSize, 0, new List<ProjectRequirementMainExtend> { }));
            }
        }
    }
}
